#默认只返回token


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }
import re
from users.models import Users

from django.contrib.auth.backends import ModelBackend

"""
1根据用户输入的账号信息 进行正则的匹配 如果满足手机号规则 ，则根据手机号查询用户
否则根据用户名查询
2 检查密码是否正确
"""
def get_user_by_account(account):
    #根据用户输入的字符串 判断是手机号还是用户名

    try:
        if re.match(r'1[345789]\d{9}',account):
            user = Users.objects.get(mobile=account)
        else:
            user = Users.objects.get(username=account)
    except Users.DoesNotExist:
        user = None

    return user

class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user
        return None


class MyBackend(object):
    def authenticate(self, request, username=None, password=None):
        # 1.根据用户输入的 账号信息 ，进行正则的匹配
        user = get_user_by_account(username)

        # 2.检查密码是否正确
        if user is not None and user.check_password(password):
            # 说明用户名和密码一致
            return user

        return None

    def get_user(self, user_id):
        try:
            return Users.objects.get(pk=user_id)
        except Users.DoesNotExist:
            return None